/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.DccrDAO;
import com.cashmate.hibernate.dao.PastDueListingDAO;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Pastduelisting;
import com.cashmate.hibernate.pojo.Summary;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Dine
 */
@Result(name = "error", type = "redirect", location = "/error/messages.jsp")
public class GridWeekperf extends ActionSupport {

    private static Logger logger = Logger.getLogger(GridWeekperf.class);
    private final DccrDAO dccrdao = (DccrDAO) ServletActionContext.getServletContext().getAttribute("dccrDAO");
//    private final LoansDAO loansdao = (LoansDAO) ServletActionContext.getServletContext().getAttribute("loansDAO");
    private final PastDueListingDAO pastdao = (PastDueListingDAO) ServletActionContext.getServletContext().getAttribute("pastdao");
    private List<Summary> gridModel;
    //get how many rows we want to have into the grid - rowNum attribute in the grid
    private Integer rows = 0;
    //Get the requested page. By default grid sets this to 1.
    private Integer page = 0;
    // sorting order - asc or desc
    private String sord;
// get index row - i.e. user click to sort.
    private String sidx;
    // Search Field
    private String searchField;
    // The Search String
    private String searchString;
    // he Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
    private String searchOper;
    // Your Total Pages
    private Integer total = 0;
    // All Record
    private Integer records = 0;
    private String branch, date;

    @Action(value = "/grid-weekperf", results = {
        @Result(name = "success", type = "json")
    })
    @Override
    public String execute() throws Exception {
        try {
            // System.out.println(branch+"asdasd");
            //max record
            int to = (rows * page);
            //offset record
//            int from = to - rows;
            //instantiate a new criteria for a POJO class
            String areacode = null;
            if (searchField != null && searchField.length() > 0) {
                if (searchField.equals("areacode")) {
                    areacode = searchString;
                }
            }

            gridModel = dccrdao.weekPerformanceProcedure(date, Integer.parseInt(branch), areacode);


            // handle Order By
            if (sidx != null && !sidx.equals("")) {
                if (sord.equals("asc")) {
                    Collections.sort(gridModel, new SummaryComparator(sidx));
                } else {
                    Collections.sort(gridModel, new SummaryComparator(sidx));
                    Collections.reverse(gridModel);
                }
            }


            //CODE FOR NON-MOVING
            Summary nm = new Summary();
            nm.setAreacode("NM");
            DetachedCriteria criteria = DetachedCriteria.forClass(Pastduelisting.class);
            criteria.add(Restrictions.eq("branchid", Integer.parseInt(branch)));
            if(areacode != null){
                criteria.add(Restrictions.like("areacode", "%"+areacode+"%"));
            }
            List<Pastduelisting> pastList = pastdao.findByCriteria(criteria);

            for (Pastduelisting p : pastList) {
                nm.setCutoffdue(nm.getCutoffdue() + p.getCutoffdue());
                nm.setOverdue(nm.getOverdue() + p.getOverdue());
                nm.setDueplusod(nm.getDueplusod() + p.getDueplusod());
                nm.setTotaladvance(nm.getTotaladvance() + p.getTotaladvance());
                nm.setDebitedpayment(nm.getDebitedpayment() + p.getDebitedpayment());
                nm.setTotalcutoffcollection(nm.getTotalcutoffcollection() + p.getTotalcutoffcollection());
            }

            nm.setPngenerated(0);
            nm.setNewacct(0);
            nm.setTotacctrel(0);

            Summary active = new Summary();
            active.setAreacode("Active");
            for (Summary s : gridModel) {
                active.setCutoffdue(active.getCutoffdue() + s.getCutoffdue());
                active.setOverdue(active.getOverdue() + s.getOverdue());
                active.setDueplusod(active.getDueplusod() + s.getDueplusod());
                active.setTotaladvance(active.getTotaladvance() + s.getTotaladvance());
                active.setDebitedpayment(active.getDebitedpayment() + s.getDebitedpayment());
                active.setTotalcutoffcollection(active.getTotalcutoffcollection() + s.getTotalcutoffcollection());
                active.setPngenerated(active.getPngenerated() + s.getPngenerated());
                active.setNewacct(active.getNewacct() + s.getNewacct());
                    active.setTotacctrel(active.getTotacctrel() + s.getTotacctrel());
            }

            Summary grandtotal = new Summary();
            grandtotal.setAreacode("Total");
            grandtotal.setCutoffdue(nm.getCutoffdue() + active.getCutoffdue());
            grandtotal.setOverdue(nm.getOverdue() + active.getOverdue());
            grandtotal.setDueplusod(nm.getDueplusod() + active.getDueplusod());
            grandtotal.setTotaladvance(nm.getTotaladvance() + active.getTotaladvance());
            grandtotal.setDebitedpayment(nm.getDebitedpayment() + active.getDebitedpayment());
            grandtotal.setTotalcutoffcollection(nm.getTotalcutoffcollection() + active.getTotalcutoffcollection());
            grandtotal.setPngenerated(active.getPngenerated());
            grandtotal.setNewacct(active.getNewacct());
            grandtotal.setTotacctrel(active.getTotacctrel());

            gridModel.add(nm);
            gridModel.add(active);
            gridModel.add(grandtotal);
            
            ServletActionContext.getRequest().getSession().setAttribute("weekperf", gridModel);
            ServletActionContext.getRequest().getSession().setAttribute("dateweekperf", date);
            records = gridModel.size();

            //gridModel = summarydao.findByCriteria(criteria, from, to);

            total = (int) Math.ceil((double) records / (double) rows);
            //logger.info(ClassUtils.toString(this));
        } catch (Exception ex) {
            Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + ex.getLocalizedMessage(), ex);
            } else {
                logger.fatal(ex.getLocalizedMessage(), ex);
            }
            ex.printStackTrace();
            addActionError(ex.getLocalizedMessage());
            return ERROR;
        } finally {
            DccrDAO.close();
            PastDueListingDAO.close();
        }
        return SUCCESS;
    }

    public List<Summary> getGridModel() {
        return gridModel;
    }

    public void setGridModel(List<Summary> gridModel) {
        this.gridModel = gridModel;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRecords() {
        return records;
    }

    public void setRecords(Integer records) {
        this.records = records;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public String getSearchField() {
        return searchField;
    }

    public void setSearchField(String searchField) {
        this.searchField = searchField;
    }

    public String getSearchOper() {
        return searchOper;
    }

    public void setSearchOper(String searchOper) {
        this.searchOper = searchOper;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public String getSidx() {
        return sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public String getSord() {
        return sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }
}

class SummaryComparator implements Comparator<Summary> {

    private String token;

    public SummaryComparator(String token) {
        this.token = token;
    }

    public int compare(Summary t, Summary t1) {
        if (token == null || token.length() < 1) {
            return 0;
        } else if (token.equals("rating")) {
            return diffDouble(t.getRating_d(), t1.getRating_d());
        } else if (token.equals("cutoffdue")) {
            return diffDouble(t.getCutoffdue(), t1.getCutoffdue());
        } else if (token.equals("overdue")) {
            return diffDouble(t.getOverdue(), t1.getOverdue());
        } else if (token.equals("dueplusod")) {
            return diffDouble(t.getDueplusod(), t1.getDueplusod());
        } else if (token.equals("totaladvance")) {
            return diffDouble(t.getTotaladvance(), t1.getTotaladvance());
        } else if (token.equals("debitedpayment")) {
            return diffDouble(t.getDebitedpayment(), t1.getDebitedpayment());
        } else if (token.equals("debitedpayment")) {
            return diffDouble(t.getDebitedpayment(), t1.getDebitedpayment());
        } else if (token.equals("computedtotalpayment")) {
            return diffDouble(t.getComputedtotalpayment(), t1.getComputedtotalpayment());
        } else if (token.equals("newacct")) {
            Integer i = new Integer(t.getNewacct());
            Integer i1 = new Integer(t1.getNewacct());
            return i.compareTo(i1);
        } else if (token.equals("totacctrel")) {
            Integer i = new Integer(t.getTotacctrel());
            Integer i1 = new Integer(t1.getTotacctrel());
            return i.compareTo(i1);
        } else {
            return t.getAreacode().compareTo(t1.getAreacode());
        }
    }

    private int diffDouble(double d1, double d2) {
        if (d1 > d2) {
            return 1;
        } else if (d1 < d2) {
            return -1;
        } else {
            return 0;
        }
    }
}
